Skip to main content

Permutation in String

Question

Given two strings s1 and s2, write a function to check if s2 contains a permutation of s1.

Example 1
Input: s = "ab"
p = "ba"

Output: True

Solution

all//Permutation in String.py


def permutationInString(str1, str2):
l1 = len(str1)
l2 = len(str2)

# Return False if strings are not of equal
# length
if l1 != l2:
return False

# Store the frequency of characters of str1 in
# a dictionary
freq = {}
for i in range(l1):
freq[str1[i]] = freq.get(str1[i], 0) + 1

# Traverse str2 to check whether all characters
# of str1 are present in str2 with same frequency
for i in range(l2):
if str2[i] not in freq.keys():
return False
else:
freq[str2[i]] = freq.get(str2[i], 0) - 1
if freq[str2[i]] < 0:
return False

return True